<?php
// +----------------------------------------------------------------------
// | HuajiBBS
// +----------------------------------------------------------------------
// | Copyright © 2022 HuajiMC. All rights reserved.
// +----------------------------------------------------------------------
// | License: GNU General Public License 3.0
// +----------------------------------------------------------------------
// | Author: 滑稽mc（HuajiMC） <HuajiMC@126.com>
// +----------------------------------------------------------------------

namespace model;
use core\Model;

class UserfollowModel extends Model {
	public $table = 'user_follow';
	private $uid1;
	private $uid2;

	const NOT_FOLLOW = 0;
	const POSITIVE_FOLLOW = 1;
	const REVERSE_FOLLOW = 2;
	const MUTUAL_FOLLOW = 3;
	
	public function uid1($uid1) {
	    $this->uid1 = $uid1;
		return $this->and("user_follow.uid1 = '{$uid1}'");
	}

	public function uid2($uid2) {
	    $this->uid2 = $uid2;
		return $this->and("user_follow.uid2 = '{$uid2}'");
	}

    public function getState() {
        return $this->total() ? true : false;
    }

    public function state() {
        $uid1 = $this->uid1;
        $uid2 = $this->uid2;
        $positive = $this->getState();
        $reverse = $this->uid1($uid2)->uid2($uid1)->getState();

        if($positive && $reverse) {
            return self::MUTUAL_FOLLOW;
        } else if($positive && ! $reverse) {
            return self::POSITIVE_FOLLOW;
        } else if(! $positive && $reverse) {
            return self::REVERSE_FOLLOW;
        } else if(! $positive && ! $reverse) {
            return self::NOT_FOLLOW;
        }
    }

    public function follow($uid1,$uid2) {
        return $this->insert(['uid1' => $uid1, 'uid2' => $uid2, 'time' => time()]) ? true : false;
    }
    
    public function follow_threads() {
        $uids = array_column($a = $this->select()->getAll(),'uid2');
        return M('thread')->and('uid in (' . implode($uids,',') . ')');
    }
    
	//Override
	public function getAll() {
		if(! $follows = $this->temp[$this->sql]) {
		    $follows = $this->result->fetch_all(MYSQLI_ASSOC);
			Temp()->set('sql_' . $this->sql,$follows);
		}
		if($follows) {
			foreach($follows as &$follow) {
				$follow['user1'] = M('user')->uid($follow['uid1'])->select('_safe_')->getOne();
				$follow['user2'] = M('user')->uid($follow['uid2'])->select('_safe_')->getOne();
				$follow['state'] = $this->uid1($follow['uid1'])->uid2($follow['uid2'])->state();
			}
		}
		return $follows;
	}
}